/*
* Copyright 2004-2010 mb_sx@hotmail.com
* All Rights Reserved.
*/
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Threading;
using System.Drawing.Printing;
using System.IO;
using DeskNotes.Utils;

namespace DeskNotes
{
	/// <summary>
	/// The form is main object which is loaded by application.
	/// It contains TaskBar notification icon and serves as handler for users
	/// action from notify icon pop up menu.
	/// </summary>
	public class MainForm : System.Windows.Forms.Form
	{
		//delegate void PrintInBackgroundDelegate();

		private delegate void ShowNotes();
        internal delegate void CallWhenShown();

		//private ShowNotes showDeskNotes;
		internal System.Windows.Forms.NotifyIcon ni;
		private System.Windows.Forms.Label label1;
        private System.ComponentModel.IContainer components;
		private System.Windows.Forms.SaveFileDialog newDataSet;
        private System.Windows.Forms.OpenFileDialog openDataSet;
        
		private DeskNotesData deskNotes;
		//NotePrintDocument myDoc;
        private System.Windows.Forms.PictureBox pictureBox1;
		private System.Windows.Forms.Button btnClose;
		private int lastMenuIndex = 0;
        private System.Windows.Forms.Label lblVersion;
        private System.Windows.Forms.PageSetupDialog pageSetupDialog;
		//private bool aboutShowed = false;
        private System.Windows.Forms.Label lblNET;
        internal ArchiveForm archiveForm = null;
        private ContextMenuStrip mainMenu;
        private ToolStripMenuItem newStripMenuItem;
        private ToolStripMenuItem showAllStripMenuItem;
        private ToolStripMenuItem synchronizeAllStripMenuItem;
        private ToolStripMenuItem hideAllStripMenuItem;
        private ToolStripMenuItem settingsStripMenuItem;
        private ToolStripMenuItem archiveStripMenuItem;
        private ToolStripMenuItem printPreviewStripMenuItem;
        private ToolStripMenuItem pageSetupStripMenuItem;
        private ToolStripMenuItem aboutStripMenuItem;
        private ToolStripMenuItem printAllStripMenuItem;
        private ToolStripMenuItem exitStripMenuItem;
        private ToolStripSeparator toolStripSeparator1;
        private ToolStripSeparator toolStripSeparator2;
        private ToolStripSeparator toolStripSeparator3;
        private ToolStripSeparator toolStripSeparator4;
        private ToolStripSeparator toolStripSeparator5;
        private ToolStripSeparator toolStripSeparator6;
        private ContextMenuStrip menuCopyInfo;
        private HelpProvider helpProvider1;
        private ToolStripMenuItem menuHelp;
        private ToolStripMenuItem copyInfoStripMenuItem;
        internal EventHandler ApplicationExitEventHandler = null;
        static internal MainForm theInstance;

        /// <summary>
        /// Form designer constructor
        /// </summary>
        public MainForm()
        {
            InitializeComponent();
            MainForm.theInstance = this;
        }

        /// <summary>
        /// Creates MainForm during runtime with all objects and properties setup
        /// </summary>
        /// <param name="deskNotes">Main data handling class DeskNotes</param>
		internal MainForm(DeskNotesData deskNotes) : this()
		{
			this.deskNotes = deskNotes;
			//Thread.CurrentThread.CurrentUICulture = new System.Globalization.CultureInfo(Properties.Settings.Default.Culture);
			
            IntPtr handle = this.Handle;
            RtfConverter.TheBox = new RichTextBox();

			lastMenuIndex = mainMenu.Items.Count;
			//Application.ApplicationExit += new EventHandler(this.OnApplicationExit);
            // get version info
            System.Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version;
            string ver = string.Format(MainResource.GetString("VERSION_INFO"), version.Major, version.Minor,
                version.Revision, version.Build);
            lblVersion.Text = ver;

            System.Version clrVersion = System.Environment.Version;
            string clr = string.Format(MainResource.GetString("CLR_VERSION_INFO"), clrVersion.Major, clrVersion.Minor, clrVersion.Revision, clrVersion.Build);
            lblNET.Text = clr;
            this.Visible = false;
 		}


        private void MainForm_Shown(object sender, EventArgs e)
        {
            Logger.WriteLine("MainForm_Shown started");
            try
            {
                this.Visible = false;
                ni.ShowBalloonTip(5000);
                // Read settings and data in async thread this allows main form to be fully painted.
                //RunWhenLoaded();
            }
            catch (Exception ex)
            {// catch any exception which can happen when working with DataSet.
                MessageBox.Show(this, MainResource.GetString("APP_ERROR") + ex.Message, MainResource.GetString("APP_TITLE"),
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            WinImports.SetForegroundWindow(this.Handle);
        }
        
        

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
           // SystemEvents.UserPreferenceChanged -= SystemEvents_UserPreferenceChanged;
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

        /// <summary>
        /// Calculates number of Twips per Pixels
        /// </summary>
        /// <param name="pixels">Number of pixels to get twips for them</param>
        /// <returns>Number of twips per pixel</returns>
        internal int GetTwipsPerPixels(long pixels)
        {
            Graphics g = this.CreateGraphics();
            IntPtr hDC = g.GetHdc();
            long pixelsPerInch = WinImports.GetDeviceCaps(hDC, WinImports.LOGPIXELSX);
            g.ReleaseHdc(hDC);
            g.Dispose();
            double twPerPix = (pixels / (double)(pixelsPerInch)) * WinImports.TwipsPerInch;
            return (int)twPerPix;
            //long pixel = (twips / nTwipsPerInch_) * pixelsPerInch;
        }

        /// <summary>
        /// Twips per pixel for application runtime determined once when 1st time requested
        /// </summary>
        static private int twipsPerPixel = 0;
        static public int TwipsPerPixel
        {
            get
            {
                if (twipsPerPixel == 0)
                    twipsPerPixel = theInstance.GetTwipsPerPixels(1);
                return twipsPerPixel;
            }
        }

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.components = new System.ComponentModel.Container();
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm));
            this.ni = new System.Windows.Forms.NotifyIcon(this.components);
            this.mainMenu = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.newStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
            this.showAllStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.synchronizeAllStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.hideAllStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
            this.settingsStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.archiveStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripSeparator3 = new System.Windows.Forms.ToolStripSeparator();
            this.printPreviewStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.printAllStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.pageSetupStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripSeparator4 = new System.Windows.Forms.ToolStripSeparator();
            this.menuHelp = new System.Windows.Forms.ToolStripMenuItem();
            this.aboutStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripSeparator5 = new System.Windows.Forms.ToolStripSeparator();
            this.exitStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripSeparator6 = new System.Windows.Forms.ToolStripSeparator();
            this.label1 = new System.Windows.Forms.Label();
            this.menuCopyInfo = new System.Windows.Forms.ContextMenuStrip(this.components);
            this.copyInfoStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.newDataSet = new System.Windows.Forms.SaveFileDialog();
            this.openDataSet = new System.Windows.Forms.OpenFileDialog();
            this.pictureBox1 = new System.Windows.Forms.PictureBox();
            this.lblVersion = new System.Windows.Forms.Label();
            this.btnClose = new System.Windows.Forms.Button();
            this.pageSetupDialog = new System.Windows.Forms.PageSetupDialog();
            this.lblNET = new System.Windows.Forms.Label();
            this.helpProvider1 = new System.Windows.Forms.HelpProvider();
            this.mainMenu.SuspendLayout();
            this.menuCopyInfo.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
            this.SuspendLayout();
            // 
            // ni
            // 
            this.ni.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info;
            resources.ApplyResources(this.ni, "ni");
            this.ni.ContextMenuStrip = this.mainMenu;
            this.ni.DoubleClick += new System.EventHandler(this.menuNew_Click);
            this.ni.MouseClick += new System.Windows.Forms.MouseEventHandler(this.ni_MouseClick);
            // 
            // mainMenu
            // 
            this.mainMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.newStripMenuItem,
            this.toolStripSeparator1,
            this.showAllStripMenuItem,
            this.synchronizeAllStripMenuItem,
            this.hideAllStripMenuItem,
            this.toolStripSeparator2,
            this.settingsStripMenuItem,
            this.archiveStripMenuItem,
            this.toolStripSeparator3,
            this.printPreviewStripMenuItem,
            this.printAllStripMenuItem,
            this.pageSetupStripMenuItem,
            this.toolStripSeparator4,
            this.menuHelp,
            this.aboutStripMenuItem,
            this.toolStripSeparator5,
            this.exitStripMenuItem,
            this.toolStripSeparator6});
            this.mainMenu.Name = "contextMenuStrip1";
            this.helpProvider1.SetShowHelp(this.mainMenu, ((bool)(resources.GetObject("mainMenu.ShowHelp"))));
            resources.ApplyResources(this.mainMenu, "mainMenu");
            this.mainMenu.Opening += new System.ComponentModel.CancelEventHandler(this.mainMenu_Opening);
            // 
            // newStripMenuItem
            // 
            resources.ApplyResources(this.newStripMenuItem, "newStripMenuItem");
            this.newStripMenuItem.Name = "newStripMenuItem";
            this.newStripMenuItem.Click += new System.EventHandler(this.menuNew_Click);
            // 
            // toolStripSeparator1
            // 
            this.toolStripSeparator1.Name = "toolStripSeparator1";
            resources.ApplyResources(this.toolStripSeparator1, "toolStripSeparator1");
            // 
            // showAllStripMenuItem
            // 
            this.showAllStripMenuItem.Name = "showAllStripMenuItem";
            resources.ApplyResources(this.showAllStripMenuItem, "showAllStripMenuItem");
            this.showAllStripMenuItem.Click += new System.EventHandler(this.menuShowAll_Click);
            // 
            // synchronizeAllStripMenuItem
            // 
            resources.ApplyResources(this.synchronizeAllStripMenuItem, "synchronizeAllStripMenuItem");
            this.synchronizeAllStripMenuItem.Name = "synchronizeAllStripMenuItem";
            this.synchronizeAllStripMenuItem.Click += new System.EventHandler(this.menuSyncAll_Click);
            // 
            // hideAllStripMenuItem
            // 
            this.hideAllStripMenuItem.Name = "hideAllStripMenuItem";
            resources.ApplyResources(this.hideAllStripMenuItem, "hideAllStripMenuItem");
            this.hideAllStripMenuItem.Click += new System.EventHandler(this.menuHideAll_Click);
            // 
            // toolStripSeparator2
            // 
            this.toolStripSeparator2.Name = "toolStripSeparator2";
            resources.ApplyResources(this.toolStripSeparator2, "toolStripSeparator2");
            // 
            // settingsStripMenuItem
            // 
            this.settingsStripMenuItem.Name = "settingsStripMenuItem";
            resources.ApplyResources(this.settingsStripMenuItem, "settingsStripMenuItem");
            this.settingsStripMenuItem.Click += new System.EventHandler(this.menuOptions_Click);
            // 
            // archiveStripMenuItem
            // 
            this.archiveStripMenuItem.Name = "archiveStripMenuItem";
            resources.ApplyResources(this.archiveStripMenuItem, "archiveStripMenuItem");
            this.archiveStripMenuItem.Click += new System.EventHandler(this.menuArchive_Click);
            // 
            // toolStripSeparator3
            // 
            this.toolStripSeparator3.Name = "toolStripSeparator3";
            resources.ApplyResources(this.toolStripSeparator3, "toolStripSeparator3");
            // 
            // printPreviewStripMenuItem
            // 
            this.printPreviewStripMenuItem.Name = "printPreviewStripMenuItem";
            resources.ApplyResources(this.printPreviewStripMenuItem, "printPreviewStripMenuItem");
            this.printPreviewStripMenuItem.Click += new System.EventHandler(this.menuPrintPreview_Click);
            // 
            // printAllStripMenuItem
            // 
            resources.ApplyResources(this.printAllStripMenuItem, "printAllStripMenuItem");
            this.printAllStripMenuItem.Name = "printAllStripMenuItem";
            this.printAllStripMenuItem.Click += new System.EventHandler(this.menuPrintAll_Click);
            // 
            // pageSetupStripMenuItem
            // 
            resources.ApplyResources(this.pageSetupStripMenuItem, "pageSetupStripMenuItem");
            this.pageSetupStripMenuItem.Name = "pageSetupStripMenuItem";
            this.pageSetupStripMenuItem.Click += new System.EventHandler(this.menuPageSetup_Click);
            // 
            // toolStripSeparator4
            // 
            this.toolStripSeparator4.Name = "toolStripSeparator4";
            resources.ApplyResources(this.toolStripSeparator4, "toolStripSeparator4");
            // 
            // menuHelp
            // 
            this.menuHelp.Name = "menuHelp";
            resources.ApplyResources(this.menuHelp, "menuHelp");
            this.menuHelp.Click += new System.EventHandler(this.menuHelp_Click);
            // 
            // aboutStripMenuItem
            // 
            this.aboutStripMenuItem.Name = "aboutStripMenuItem";
            resources.ApplyResources(this.aboutStripMenuItem, "aboutStripMenuItem");
            this.aboutStripMenuItem.Click += new System.EventHandler(this.menuAbout_Click);
            // 
            // toolStripSeparator5
            // 
            this.toolStripSeparator5.Name = "toolStripSeparator5";
            resources.ApplyResources(this.toolStripSeparator5, "toolStripSeparator5");
            // 
            // exitStripMenuItem
            // 
            this.exitStripMenuItem.Name = "exitStripMenuItem";
            resources.ApplyResources(this.exitStripMenuItem, "exitStripMenuItem");
            this.exitStripMenuItem.Click += new System.EventHandler(this.ExitSelected);
            // 
            // toolStripSeparator6
            // 
            this.toolStripSeparator6.Name = "toolStripSeparator6";
            resources.ApplyResources(this.toolStripSeparator6, "toolStripSeparator6");
            // 
            // label1
            // 
            this.label1.ContextMenuStrip = this.menuCopyInfo;
            resources.ApplyResources(this.label1, "label1");
            this.label1.Name = "label1";
            this.helpProvider1.SetShowHelp(this.label1, ((bool)(resources.GetObject("label1.ShowHelp"))));
            // 
            // menuCopyInfo
            // 
            this.menuCopyInfo.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.copyInfoStripMenuItem});
            this.menuCopyInfo.Name = "menuCopyInfo";
            this.helpProvider1.SetShowHelp(this.menuCopyInfo, ((bool)(resources.GetObject("menuCopyInfo.ShowHelp"))));
            resources.ApplyResources(this.menuCopyInfo, "menuCopyInfo");
            // 
            // copyInfoStripMenuItem
            // 
            resources.ApplyResources(this.copyInfoStripMenuItem, "copyInfoStripMenuItem");
            this.copyInfoStripMenuItem.Name = "copyInfoStripMenuItem";
            this.copyInfoStripMenuItem.Click += new System.EventHandler(this.menuCopy_Click);
            // 
            // newDataSet
            // 
            this.newDataSet.DefaultExt = "xml";
            this.newDataSet.FileName = "Notes.xml";
            resources.ApplyResources(this.newDataSet, "newDataSet");
            // 
            // openDataSet
            // 
            this.openDataSet.DefaultExt = "xml";
            this.openDataSet.FileName = "Notes.xml";
            resources.ApplyResources(this.openDataSet, "openDataSet");
            // 
            // pictureBox1
            // 
            this.pictureBox1.ContextMenuStrip = this.menuCopyInfo;
            resources.ApplyResources(this.pictureBox1, "pictureBox1");
            this.pictureBox1.Name = "pictureBox1";
            this.helpProvider1.SetShowHelp(this.pictureBox1, ((bool)(resources.GetObject("pictureBox1.ShowHelp"))));
            this.pictureBox1.TabStop = false;
            // 
            // lblVersion
            // 
            this.lblVersion.ContextMenuStrip = this.menuCopyInfo;
            resources.ApplyResources(this.lblVersion, "lblVersion");
            this.lblVersion.Name = "lblVersion";
            this.helpProvider1.SetShowHelp(this.lblVersion, ((bool)(resources.GetObject("lblVersion.ShowHelp"))));
            // 
            // btnClose
            // 
            resources.ApplyResources(this.btnClose, "btnClose");
            this.btnClose.Name = "btnClose";
            this.helpProvider1.SetShowHelp(this.btnClose, ((bool)(resources.GetObject("btnClose.ShowHelp"))));
            this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
            // 
            // pageSetupDialog
            // 
            this.pageSetupDialog.MinMargins = new System.Drawing.Printing.Margins(10, 10, 10, 10);
            // 
            // lblNET
            // 
            this.lblNET.ContextMenuStrip = this.menuCopyInfo;
            resources.ApplyResources(this.lblNET, "lblNET");
            this.lblNET.Name = "lblNET";
            this.helpProvider1.SetShowHelp(this.lblNET, ((bool)(resources.GetObject("lblNET.ShowHelp"))));
            // 
            // helpProvider1
            // 
            resources.ApplyResources(this.helpProvider1, "helpProvider1");
            // 
            // MainForm
            // 
            resources.ApplyResources(this, "$this");
            this.ContextMenuStrip = this.menuCopyInfo;
            this.ControlBox = false;
            this.Controls.Add(this.lblNET);
            this.Controls.Add(this.btnClose);
            this.Controls.Add(this.lblVersion);
            this.Controls.Add(this.pictureBox1);
            this.Controls.Add(this.label1);
            this.helpProvider1.SetHelpKeyword(this, resources.GetString("$this.HelpKeyword"));
            this.helpProvider1.SetHelpNavigator(this, ((System.Windows.Forms.HelpNavigator)(resources.GetObject("$this.HelpNavigator"))));
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.Name = "MainForm";
            this.helpProvider1.SetShowHelp(this, ((bool)(resources.GetObject("$this.ShowHelp"))));
            this.ShowInTaskbar = false;
            this.WindowState = System.Windows.Forms.FormWindowState.Minimized;
            this.Shown += new System.EventHandler(this.MainForm_Shown);
            this.mainMenu.ResumeLayout(false);
            this.menuCopyInfo.ResumeLayout(false);
            ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
            this.ResumeLayout(false);

		}
		#endregion
		

		/// <summary>
		/// When context menu Exit is selected then initiate application exit
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		public void ExitSelected(object sender, System.EventArgs e)
		{
			//deskNotes.Exit();
			Application.Exit();
		}
		/// <summary>
		/// Removes notification area icon.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		/*private void OnApplicationExit(object sender, EventArgs e) 
		{
			
            try
            {
                ni.Visible = false;
            }
            catch  { //do nothing
            }
		}
        */


		private void menuOptions_Click(object sender, System.EventArgs e)
		{
            this.settingsStripMenuItem.Enabled = false;
            try
            {
                Properties.Settings config = Properties.Settings.Default;
                //config.Reload();

                SettingsDialog settings = new SettingsDialog();
                settings.lblFont.BackColor = config.BackgroundColor;
                settings.lblFont.ForeColor = config.TextColor;
                settings.lblFont.Font = config.Font;
                settings.SetPreviewColors(config.TextColor, config.BackgroundColor);
                settings.chkInsertOnlyDate.Checked = config.InsertOnlyDate;
                settings.chkSound.Checked = deskNotes.PlaySound;
                settings.comboLanguage.SelectedItem = new System.Globalization.CultureInfo(config.Culture).NativeName;
                settings.dataStorage.DataFileName = config.DataFile;
                settings.dataStorage.ArchiveFileName = config.ArchiveFile;
                settings.chkRemoveOutlook.Checked = config.RemoveInOutlook;
                settings.chkNewSwitchable.Checked = config.NewSwitchable;
                settings.chkFloatingCaption.Checked = config.DynamicCaption;


                if (config.DragDropToArchive)
                    settings.rbDragDrop.Checked = true;
                else
                    settings.rbArchive.Checked = true;

                if (deskNotes.PlaySound)
                    settings.txtSound.Text = config.SoundFile;
                else
                {
                    settings.txtSound.Enabled = false;
                    settings.btnSound.Enabled = false;
                }
                if (DialogResult.OK == settings.ShowDialog(this))
                {
                    this.settingsStripMenuItem.Enabled = true;
                    if (settings.lblFont.BackColor != config.BackgroundColor)
                        config.BackgroundColor = settings.lblFont.BackColor;
                    if (settings.lblFont.ForeColor != config.TextColor)
                        config.TextColor = settings.lblFont.ForeColor;
                    if (settings.lblFont.Font != config.Font)
                        config.Font = settings.lblFont.Font;

                    if (config.InsertOnlyDate != settings.chkInsertOnlyDate.Checked)
                        config.InsertOnlyDate = settings.chkInsertOnlyDate.Checked;

                    if (config.DragDropToArchive != settings.rbDragDrop.Checked)
                        config.DragDropToArchive = settings.rbDragDrop.Checked;

                    if (config.RemoveInOutlook != settings.chkRemoveOutlook.Checked)
                        config.RemoveInOutlook = settings.chkRemoveOutlook.Checked;

                    if (config.NewSwitchable != settings.chkNewSwitchable.Checked)
                        config.NewSwitchable = settings.chkNewSwitchable.Checked;

                    config.SoundFile = (settings.chkSound.Checked) && (config.SoundFile != settings.txtSound.Text) ?
                        settings.txtSound.Text : null;
                    if (0 == settings.comboLanguage.SelectedIndex)
                        config.Culture = "en-US";
                    else
                        config.Culture = "cs-CZ";

                    if (config.DynamicCaption != settings.chkFloatingCaption.Checked)
                        config.DynamicCaption = settings.chkFloatingCaption.Checked;

                    // Settings requiring restart of application.
                    bool restart = false;

                    // If following settings changed then DeskNotes has to be restarted.
                    if ((settings.dataStorage.DataFileName != config.DataFile) &&
                        (settings.dataStorage.DataFileName != ""))
                        restart = true;
                    if ((settings.dataStorage.ArchiveFileName != config.ArchiveFile) &&
                        (settings.dataStorage.ArchiveFileName != ""))
                        restart = true;


                    if (restart)
                    {
                        if (DialogResult.Yes == MessageBox.Show(Resources.AppResource.APP_RESTART, Resources.AppResource.APP_TITLE,
                                MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2))
                        {
                            deskNotes.Save();
                            deskNotes.SaveArchive();
                            config.DataFile = settings.dataStorage.DataFileName;
                            config.ArchiveFile = settings.dataStorage.ArchiveFileName;
                            config.Save();
                            Application.ApplicationExit -= this.ApplicationExitEventHandler; //this.OnApplicationExit;
                            // Restart() causes process to hold (lock) Settings file if product is running inside debugger.
                            // This is OK when run outside of debugger then settings are not locked and they are correctly read
                            // during subsequent start.
                            Application.Restart();
                            return;
                        }
                    }
                }
                config.Save();
            }
           finally  // just make sure menu is enabled when something wrong happens 
           {
                this.settingsStripMenuItem.Enabled = true;
           }
		}

		/// <summary>
		/// Method creates a new note in a default position.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuNew_Click(object sender, System.EventArgs e)
		{
			Note n = deskNotes.CreateNewNote(MainResource.GetString("FIRST_NOTE"), Note.DefaultPosition);
            n.MyForm.Activate();
            n.MyForm.SetResizableBorder();
		}

		/// <summary>
		/// Brings all desknotes incl. hidden ones to front of the user above all other 
		/// windows displayed on desktop.
		/// </summary
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuShowAll_Click(object sender, System.EventArgs e)
		{
			IEnumerator myEnum = deskNotes.GetEnumerator();
			deskNotes.ShowingAllNotes = true;
            NoteForm lastActive = deskNotes.LastActiveForm;
			while (myEnum.MoveNext())
			{
				Note n = (Note) myEnum.Current;
				//create forms for hidden DeskNotes
                if (n.Hidden)
                {
                    n.Hidden = false;
                    n.MyForm.Show();
                    n.MyForm.RemoveCaption();
                }
                else
                    n.MyForm.Activate();
			}
			// Top most note is reset when note is added. It needs to
			// be set again after creation.
			deskNotes.ConfirmTopMost();
            if (null == lastActive)
                return;
            if (lastActive.Visible)
            {
                lastActive.Activate();
                lastActive.SetResizableBorder();
            }
			deskNotes.ShowingAllNotes = false;
		}

		/// <summary>
		/// Hides all notes currently visible
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuHideAll_Click(object sender, System.EventArgs e)
		{
			IEnumerator myEnum = deskNotes.GetEnumerator();
			while (myEnum.MoveNext())
			{
				Note n = (Note) myEnum.Current;
				//create forms for hidden DeskNotes
				n.Hidden = true;
			}
		}

        /// <summary>
        /// Activates all visible desknotes when notification icon is single clicked.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ni_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button != MouseButtons.Right)
            {
                Logger.WriteLine("Notification icon Clicked, activating visible forms");
                //remember last active form, before all visible forms are activated here
                deskNotes.GroupFormsActivation = true;
                NoteForm lastActive = deskNotes.LastActiveForm;
                IEnumerator myEnum = deskNotes.GetEnumerator();
                while (myEnum.MoveNext())
                {
                    Note n = (Note)myEnum.Current;
                    if ((!n.Hidden) && (!n.MyForm.Equals(lastActive)))
                        n.MyForm.Activate();
                }
                deskNotes.GroupFormsActivation = false;
                //Activate the form which had focus before group activation and give it resizable border.
                if (null == lastActive)
                    return;
                if (lastActive.Visible)
                {
                    lastActive.Activate();
                    lastActive.SetResizableBorder();
                }
            }
        }
		
        /// <summary>
        ///  Synchronizes all DeskNotes with their Outlook copies
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void menuSyncAll_Click(object sender, EventArgs e)
        {
            IEnumerator myEnum = deskNotes.GetEnumerator();
            SynchronizationConflictDlg.Result result, nextResult = SynchronizationConflictDlg.Result.SyncAll;
            try
            {
                while (myEnum.MoveNext())
                {
                    Note n = (Note)myEnum.Current;
                    if (null != n.OutlookEntryID)
                    {
                        result = n.SynchronizeOutlook(this, ref nextResult);
                        if (SynchronizationConflictDlg.Result.Cancel == nextResult)
                        {
                            return;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Show error dialog for Outlook integration
                MessageBox.Show(Resources.AppResource.OutlookError + ex.Message, Resources.AppResource.APP_TITLE,
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

		

		/// <summary>
		/// Display MainForm like About dialog box.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuAbout_Click(object sender, System.EventArgs e)
		{
			this.Visible = true;
            this.ShowInTaskbar = true;
            this.WindowState = FormWindowState.Normal;
		}

		private void btnClose_Click(object sender, System.EventArgs e)
		{
			this.Visible = false;
            this.ShowInTaskbar = false;
		}
		/// <summary>
		/// Shows standard Page setup dialog and saves page settings into
		/// DeskNotes.pageSettings property for later use when printing.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuPageSetup_Click(object sender, System.EventArgs e)
		{
			try 
			{
				pageSetupDialog.PageSettings = deskNotes.DisplayedPageSettings;
				//System.Logger.WriteLine("Margins: {0},{1},{2},{3}",deskNotes.pageSettings.Margins.Left,
				//	deskNotes.pageSettings.Margins.Top, deskNotes.pageSettings.Margins.Right, deskNotes.pageSettings.Margins.Bottom);
			
				if (DialogResult.OK == pageSetupDialog.ShowDialog(this))
				{
					deskNotes.PageSettings = pageSetupDialog.PageSettings;
				//	System.Logger.WriteLine("Margins: {0},{1},{2},{3}",deskNotes.pageSettings.Margins.Left,
				//		deskNotes.pageSettings.Margins.Top, deskNotes.pageSettings.Margins.Right, deskNotes.pageSettings.Margins.Bottom);

				}
			} 
			catch (InvalidPrinterException)
			{
				MessageBox.Show(this, MainResource.GetString("PRINTER_NOT_AVAILABLE"), MainResource.GetString("APP_TITLE"),
					MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}
        
		private void menuPrintAll_Click(object sender, System.EventArgs e)
		{
			try 
			{
				Note[] notes = new Note[deskNotes.Count];
				deskNotes.CopyTo(notes);
				deskNotes.PrintNotes(notes, (ToolStripMenuItem) sender, printPreviewStripMenuItem);
			} 
			catch (InvalidPrinterException ex)
			{
				MessageBox.Show(this, string.Format(MainResource.GetString("PRINTER_NOT_AVAILABLE"), ex.Message),
					MainResource.GetString("APP_TITLE"), MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		

		private void menuPrintPreview_Click(object sender, System.EventArgs e)
		{
			try 
			{
				Note[] notes = new Note[deskNotes.Count];
				deskNotes.CopyTo(notes);
                CoolPrintPreview.CoolPrintPreviewDialog printPreview = new CoolPrintPreview.CoolPrintPreviewDialog(deskNotes, notes);
				printPreview.Show();
			} 
			catch (InvalidPrinterException ex)
			{
				MessageBox.Show(this, string.Format(MainResource.GetString("PRINTER_NOT_AVAILABLE"), ex.Message),
					MainResource.GetString("APP_TITLE"), MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
		}

		/// <summary>
		/// Opens ArchiveForm
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void menuArchive_Click(object sender, System.EventArgs e)
		{
			deskNotes.ShowingAllNotes = true;
			//Load archive into memory
			if (deskNotes.LoadArchive())
			{
				//If archive was loaded then open archive form
				if (null == archiveForm)
				{
					archiveForm = new ArchiveForm(deskNotes);
					archiveForm.Disposed += new EventHandler(archiveForm_Disposed);
				}
				
				archiveForm.Show();
			}
			deskNotes.ShowingAllNotes = false;
		}
		/// <summary>
		/// ArchiveForm is disposed set this class holder to null.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void archiveForm_Disposed(object sender, EventArgs e)
		{
			archiveForm = null;
		}

		private void ni_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e)
		{
			if (MouseButtons.Left == e.Button)
			{
				Logger.WriteLine("Notification area icon mouse down.");
				IEnumerator myEnum = deskNotes.GetEnumerator();
				while(myEnum.MoveNext())
				{
					Note n = (Note) myEnum.Current;
					n.MyForm.sendBack = false;
				}
			}
		}

		private void menuItem1_Select(object sender, System.EventArgs e)
		{
			WinImports.MessageBeep(WinImports.IconQuestion);
		}

		private void menuCopy_Click(object sender, System.EventArgs e)
		{
			System.Text.StringBuilder text = new System.Text.StringBuilder(150);
			text.Append("DeskNotes ");
			text.Append(lblVersion.Text);
			text.Append("\r\n");
			text.Append(lblNET.Text);
			text.Append("\r\n");
			text.Append(Environment.OSVersion);
			Clipboard.SetDataObject(text.ToString(),true);
		}

       

        private void mainMenu_Opening(object sender, CancelEventArgs e)
        {
            Logger.WriteLine("mainMenu_Opening started");
            // remove menu items representing desknotes 
            int currentMenuCount = mainMenu.Items.Count;
            for (int i = currentMenuCount; i > lastMenuIndex; i--)
            {
                mainMenu.Items.RemoveAt(i - 1);
            }
            //Logger.WriteLine("mainMenu_Opening notes menu items removed");
            //add menu items representing desknotes
            if (deskNotes.Count == 0)
                return;

            //int count = lastMenuIndex;
            //mainMenu.Items.Add(new ToolStripSeparator());
            ToolStripMenuItem menuItem;
            IEnumerator myEnum = deskNotes.GetEnumerator();
            //Bitmap icon = Properties.Resources.tray.ToBitmap();
            Bitmap iconHidden = Properties.Resources.tray_hidden.ToBitmap();
            Logger.WriteLine("mainMenu_Opening adding notes into menu");
            while (myEnum.MoveNext())
            {
                Note n = (Note)myEnum.Current;
                string tipText = n.MyForm.TextEx;
                string menuText = tipText.Length > 20 ? tipText.Substring(0, 17) + "..." : tipText;
                menuText = menuText.Replace("\n", " ");
                tipText = tipText.Length > 70 ? tipText.Substring(0, 67) + "..." : tipText;
                menuItem = new ToolStripMenuItem(menuText);
                menuItem.ToolTipText = tipText;
                if (n.Hidden)
                    menuItem.Image = iconHidden;
                else
                    menuItem.Image = n.MyForm.coloredIcon.Get;
                menuItem.Click += new EventHandler(n.MyForm.ShowMeIndirectly);
                mainMenu.Items.Add(menuItem);
                //Logger.WriteLine("mainMenu_Opening note {0} added into menu", menuText);
                
            }
            Logger.WriteLine("mainMenu_Opening completed");
        }

        private void menuHelp_Click(object sender, EventArgs e)
        {
            Help.ShowHelp(this, helpProvider1.HelpNamespace);
        }

       	
	}
}
